package com.cec.interceptor;

import com.cec.context.BaseContext;
import com.cec.exception.InvalidTokenException;
import com.cec.properties.JwtProperties;
import com.cec.result.ResultCode;
import com.cec.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class JwtTokenUserInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorizationHeader = request.getHeader("Authorization");
        if (authorizationHeader == null)
            throw new InvalidTokenException(ResultCode.NOT_LOGIN);
        String token = authorizationHeader.replace("Bearer ", "");

        log.info("token-->{}", token);
        if (token == null)
            throw new InvalidTokenException(ResultCode.INVALID_TOKEN);
        //2、校验令牌
        try {
            Claims claims = JwtUtil.parserToken(jwtProperties.getUserSecretKey(), token);
            Integer userId = Integer.valueOf(claims.get("userId").toString());
            BaseContext.setCurrentId(userId);
        } catch (Exception ex) {
            //log.info("拦截器捕获异常");
            //4、不通过，响应401状态码
            //response.setStatus(401);
            //return false;
            throw new InvalidTokenException(ResultCode.TOKEN_EXPIRED);
        }
        return true;
    }
}